<template>
  <!--el的标签看成div-->
  <!--主容器-->
  <el-main>
    <!-- 搜索栏   element ui的标签，就当做普通的div就可以，只是他添加了一些属性
    :model:  form表单绑定的数据，通常是一个对象
    :rules: form表单验证的规则
    ref :  类似form的id，是唯一的
    label-width：表单文字标签的宽度
    :inline ： 是否同一行显示
    size: 表单内组件的大小
     -->
    <el-form :model="listParameter" ref="searchRef" label-width="80px;" :inline="true" size="small">
      <el-form-item>
        <el-input v-model="listParameter.nickName" placeholder="请输入姓名"></el-input>
      </el-form-item>
      <el-form-item>
        <el-input v-model="listParameter.phone" placeholder="请输入电话"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" round icon="el-icon-search" @click="searchBtn">搜索</el-button>
        <el-button type="danger" round icon="el-icon-delete" @click="resetBtn">重置</el-button>
        <el-button v-permission="['sys:user:add']" type="success" round icon="el-icon-plus" @click="addBtn">新增</el-button>
      </el-form-item>
    </el-form>
    <!--表格-->
    <el-table :height="tableHeight" :data="tableData" :default-sort="{prop:'tableData','order':'descending',}" border
              stripe
    >
      <el-table-column sortable prop="nickName" label="姓名" width="180"></el-table-column>
      <el-table-column sortable prop="phone" label="电话" width="180"></el-table-column>
      <el-table-column sortable prop="email" label="邮箱"></el-table-column>
      <el-table-column sortable prop="username" label="账号"></el-table-column>
      <el-table-column sortable prop="sex" label="性别">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.sex == '0'">男</el-tag>
          <el-tag v-if="scope.row.sex == '1'" type="success">女</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="180px;">
        <template slot-scope="scope">
          <el-button v-permission="['sys:user:edit']" type="primary" icon="el-icon-edit" size="small" @click="editBtn(scope.row)">编辑</el-button>
          <el-button v-permission="['sys:user:delete']" type="danger" icon="el-icon-delete" size="small" @click="deleteBtn(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--分页-->
    <el-pagination
      @size-change="sizeChange"
      @current-change="currentChange"
      :current-page.sync="listParameter.currentPage"
      :page-sizes="[10,20,40,60,80,100]"
      :page-size="listParameter.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="listParameter.total" background
    >
    </el-pagination>
    <div>
      <sys-dialog
        :title="dialog.title"
        :visible="dialog.visible"
        :width="dialog.width"
        :height="dialog.height"
        @onClose="onClose"
        @onConfirm="onConfirm"
      >
        <div slot="content">
          <!-- form表单
          el-form ： 当做普通的form标签
          model ： 表单数据对象
          ref : 相当于div的id,唯一的
          rules : 表单验证规则
          label-width ： 表单域标签的宽度
          inline ： 是否在同一行显示，如果和el-row使用的时候，不需要添加该属性
          size ： 尺寸
          el-form-item ： 当做普通的div，
           -->
          <el-form
            :model="addModel"
            ref="addRef"
            :rules="rules"
            label-width="60px"
            size="small"
            style="margin-right: 20px"
          >
            <el-row>
              <el-col :span="12" :offset="0">
                <el-form-item prop="nickName" label="姓名">
                  <el-input v-model="addModel.nickName"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12" :offset="0">
                <el-form-item prop="phone" label="电话">
                  <el-input v-model="addModel.phone"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12" :offset="0">
                <el-form-item prop="email" label="邮箱">
                  <el-input v-model="addModel.email"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12" :offset="0">
                <el-form-item prop="sex" label="性别">
                  <el-radio-group v-model="addModel.sex">
                    <el-radio :label="'0'">男</el-radio>
                    <el-radio :label="'1'">女</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12" :offset="0">
                <el-form-item prop="username" label="账户">
                  <el-input v-model="addModel.username"></el-input>
                </el-form-item>
              </el-col>
              <el-col v-if="addModel.type==0" :span="12" :offset="0">
                <el-form-item prop="password" label="密码">
                  <el-input v-model="addModel.password" show-password></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12" :offset="0">
                <el-form-item prop="roleId" label="角色">
                  <el-select v-model="addModel.roleId" placeholder="请选择">
                    <el-option
                      v-for="item in options"
                      :key="item.roleId"
                      :label="item.roleName"
                      :value="item.roleId"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </sys-dialog>
    </div>
  </el-main>
</template>
<script>
import { addUserApi, editUserApi, getListApi, deleteUserApi, getRoleIdApi, getRoleListApi } from '@/api/user'
import { validatePhone, validateEmail } from '@/utils/validate'
//引入弹框组件
import SysDialog from '@/components/dialog/SysDialog'

export default {
  components: {
    SysDialog
  },
  data () {
    return {
      options: [],
      //表格高度
      tableHeight: 0,
      //表单验证规则
      rules: {
        nickName: [{
          trigger: 'blur',
          required: true,
          message: '请填写姓名！'
        }],
        phone: [{
          trigger: 'blur',
          required: true,
          message: '请填写电话！'
        }, {
          validator: validatePhone, trigger: 'blur'
        }],
        email: [{
          trigger: 'blur',
          required: true,
          message: '请填写邮箱！'
        }, {
          validator: validateEmail, trigger: 'blur'
        }],
        sex: [{
          trigger: 'change',
          required: true,
          message: '请选择性别！'
        }],
        username: [{
          trigger: 'blur',
          required: true,
          message: '请填写账户！'
        }],
        password: [{
          trigger: 'blur',
          required: true,
          message: '请填写密码！'
        }],
        roleId: [{
          trigger: 'change',
          required: true,
          message: '请选择角色！'
        }]
      },
      //表单绑定数据
      addModel: {
        roleId: '',
        type: '',//0是新增,1是编辑
        userId: '',
        nickName: '',
        phone: '',
        email: '',
        sex: '',
        username: '',
        password: ''
      },
      //弹窗属性
      dialog: {
        visible: false,
        width: 600,
        height: 200
      },
      //列表查询参数
      listParameter: {
        nickName: '',
        phone: '',
        currentPage: 1,//第一页
        pageSize: 10,//每页10条
        total: 0//总共多少条
      },
      //表格的数据
      tableData: []
    }
  },
  //进来调用
  created () {
    this.getList()
    this.getRoleList()
  },
  methods: {
    async getRoleId (userId) {
      let res = await getRoleIdApi({ userId: userId })
      if (res && res.code == 200) {
        this.addModel.roleId = res.data.roleId
      }
    },
    async getRoleList () {
      let res = await getRoleListApi()
      this.options = res.data
    },
    //搜索按钮
    searchBtn () {
      this.getList()
    },
    //重置按钮
    resetBtn () {
      this.listParameter.nickName = ''
      this.listParameter.phone = ''
      this.getList()
    },
    //获取列表
    async getList () {
      let res = await getListApi(this.listParameter)
      if (res && res.code === 200) {
        this.tableData = res.data.records
        this.listParameter.total = res.data.total
      }
    },
    //添加按钮
    addBtn () {
      //设置弹框属性
      this.dialog.title = '新增用户'
      this.dialog.visible = true
      //设置新增
      this.addModel.type = 0
      //清空表单
      this.$resetForm('addRef', this.addModel)
    },
    //编辑按钮
    editBtn (row) {
      this.dialog.title = '编辑用户'
      this.dialog.visible = true
      //设置编辑
      this.addModel.type = 1
      //清空表单
      this.$resetForm('addRef', this.addModel)
      //把要编辑的数据回显到表格中
      this.$objCoppy(row, this.addModel)
      this.getRoleId(row.userId)
    },
    //删除按钮
    async deleteBtn (row) {
      let confirm = await this.$myconfirm('确定删除数据吗?')
      if (confirm) {
        let res = await deleteUserApi({ userId: row.userId })
        if (res && res.code == 200) {
          //信息提示
          this.$message({ type: 'success', message: res.msg })
          //刷新表格
          await this.getList()
        }
      }
    },

    //页容量改变是触发
    sizeChange (val) {
      this.listParameter.pageSize = val
      this.getList()
    },
    //当前页改变触发
    currentChange (val) {
      this.listParameter.currentPage = val
      this.getList()
    },
    //弹框取消事件
    onClose () {
      this.dialog.visible = false
    },
    //弹框确认事件
    onConfirm () {
      //表单验证 valid是ture或false
      this.$refs.addRef.validate(async(valid) => {
        //添加和修改的判断
        if (valid) {
          let res = null
          if (this.addModel.type == 0) {
            res = await addUserApi(this.addModel)
          } else {
            res = await editUserApi(this.addModel)
          }
          if (res && res.code === 200) {
            //信息提示
            this.$message({ type: 'success', message: res.msg })
            //刷新表格
            await this.getList()
            //关闭弹窗
            this.dialog.visible = false
          }
        }
      })
    }
  },
  mounted () {
    this.$nextTick(() => {
      this.tableHeight = window.innerHeight - 207
    })
  }
}
</script>

<style scoped>

</style>
